package com.jilian.powerstation.modul.natives;

import android.app.Dialog;
import android.os.Handler;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jilian.powerstation.MyApplication;
import com.jilian.powerstation.R;
import com.jilian.powerstation.base.BaseActivity;
import com.jilian.powerstation.common.event.MessageEvent;
import com.jilian.powerstation.dialog.nicedialog.BaseNiceDialog;
import com.jilian.powerstation.dialog.nicedialog.NiceDialog;
import com.jilian.powerstation.dialog.nicedialog.ViewConvertListener;
import com.jilian.powerstation.dialog.nicedialog.ViewHolder;
import com.jilian.powerstation.http.SocketConfig;
import com.jilian.powerstation.http.SocketUtils;
import com.jilian.powerstation.utils.DataUtils;
import com.jilian.powerstation.utils.EmptyUtils;
import com.jilian.powerstation.utils.NumberUtils;
import com.jilian.powerstation.utils.PinziDialogUtils;
import com.jilian.powerstation.utils.RxTimerUtil;
import com.jilian.powerstation.utils.ToastUitl;
import com.jilian.powerstation.utils.TwoPointLengthFilter;
import com.jilian.powerstation.utils.rxjava.RxBus;
import com.jilian.powerstation.utils.rxjava.RxBusBean;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Arrays;
import java.util.List;

import io.reactivex.functions.Consumer;

/**
 * 电网电压响应设置
 */
public class VoltResponseModeActivity extends BaseActivity {
    private LinearLayout llOne;
    private TextView tv01;
    private RelativeLayout llTwo;
    private TextView tvTwo;
    private EditText tv02;
    private EditText tv03;


    private TextView tvRight;


    @Override
    protected void createViewModel() {

    }

    @Override
    public int intiLayout() {
        return R.layout.activity_voltresponsemode;
    }

    @Override
    public void initView() {
        setNormalTitle("Grid voltage respons setting", v -> finish());
        setrightTitle("Save", "#3298db", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                VoltResponseModeSetting();
            }
        });
        llOne = (LinearLayout) findViewById(R.id.ll_one);
        tv01 = (TextView) findViewById(R.id.tv_01);
        llTwo = (RelativeLayout) findViewById(R.id.ll_two);
        tvTwo = (TextView) findViewById(R.id.tv_two);
        tv02 = (EditText) findViewById(R.id.tv_02);
        tv03 = (EditText) findViewById(R.id.tv_03);
        tvRight = (TextView) findViewById(R.id.tv_right);

    }
    private boolean isSetting;
    /**
     * 设置
     */
    private void VoltResponseModeSetting() {

        /**
         * 小数
         */
        if (be == 2) {
            if (!TextUtils.isEmpty(tv02.getText().toString())) {
                bb = (int) (Double.parseDouble(tv02.getText().toString()) * 100);
            } else {
                bb = 0;
            }
        }
        //整数
        if (be == 3) {
            if (!TextUtils.isEmpty(tv03.getText().toString())) {
                bc = Integer.parseInt(tv03.getText().toString());
            } else {
                bc = 0;
            }
        }
        isSetting = true;
        RxTimerUtil.cancel();
        RxTimerUtil.timer(16000, new RxTimerUtil.IRxNext() {
            @Override
            public void doNext() {
                if(isSetting){
                    getLoadingDialog().dismiss();
                    ToastUitl.showImageToastTips("Time timeout");
                }
            }
        });
        getLoadingDialog().showDialog();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("响应模式", ":---- " + DataUtils.hexBytesToString(SocketConfig.voltResponseModeSetting(bc, bb, be)));
                        SocketUtils.sendSerialPort(SocketConfig.voltResponseModeSetting(bc, bb, be));
                    }
                }).start();

            }
        }, 10);

    }

    @Override
    public void initData() {
        EventBus.getDefault().register(this);
        sandMessage();

    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        MyApplication.removeActivity(this);

    }

    private boolean isChange;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        // 当按下返回键时所执行的命令
        if (keyCode == KeyEvent.KEYCODE_BACK && isChange) {
            // 此处写你按返回键之后要执行的事件的逻辑
            showLeaveDialog();
            return false;

        }
        return super.onKeyDown(keyCode, event);

    }

    @Override
    public void initListener() {
        tv02.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                isChange = true;
            }
        });
        tv03.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                isChange = true;
            }
        });
        findViewById(R.id.v_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isChange) {
                    showLeaveDialog();
                } else {
                    finish();
                }
            }
        });
        llOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showVoltResponseModeDialog();
            }
        });
    }

    /**
     * 安规标准
     */
    private void showVoltResponseModeDialog() {
        NiceDialog.init()
                .setLayoutId(R.layout.dialog_voltresponsemode_select)
                .setConvertListener(new ViewConvertListener() {
                    @Override
                    public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
                        dialog.setOutCancel(false);
                        TextView btnOne = (TextView) holder.getView(R.id.btn_one);
                        TextView btnTwo = (TextView) holder.getView(R.id.btn_two);
                        TextView btnThree = (TextView) holder.getView(R.id.btn_three);
                        TextView btnFour = (TextView) holder.getView(R.id.btn_four);
                        TextView btnFive = (TextView) holder.getView(R.id.btn_five);
                        TextView btnCancel = (TextView) holder.getView(R.id.btn_cancel);

                        btnCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                dialog.dismiss();
                            }
                        });
                        btnOne.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                                be = 0;
                                intSelectView();

                            }
                        });
                        btnTwo.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                dialog.dismiss();
                                be = 1;
                                intSelectView();

                            }
                        });

                        btnThree.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                dialog.dismiss();
                                be = 2;
                                intSelectView();

                            }
                        });
                        btnFour.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                dialog.dismiss();
                                be = 3;
                                intSelectView();

                            }
                        });
                        btnFive.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                dialog.dismiss();
                                be = 4;
                                intSelectView();
                            }
                        });


                    }
                })
                .setShowBottom(true)
                .show(getSupportFragmentManager());
    }

    //熊浪添加RxBus工具类，页面销毁时需要取消注册，否则会有内存泄漏
    private boolean isGetData;
    private String errors[] = new String[]{"Configuration is complete", "After finishing the configuration, power down and restart the device.", "After finishing the configuration, restart in operating mode.", "Disable services for system configuration", "Unable to configure in transparent transmission upgrade", "Parameter out of range", "Parameter ID is not defined", "Parameter conflict, please check"};


    private int bc, bb, be;

    private void intSelectView() {
        switch (be) {
            case 0:
                tv01.setText("Voltage active response mode");
                llTwo.setVisibility(View.GONE);
                tvRight.setVisibility(View.GONE);
                isChange = false;
                break;
            case 1:
                tv01.setText("Voltage reactive response mode");
                llTwo.setVisibility(View.GONE);
                tvTwo.setText("FixedPFMode");
                tvRight.setVisibility(View.GONE);
                isChange = false;
                break;
            case 2:
                tv01.setText("Fixed power factor mode");
                llTwo.setVisibility(View.VISIBLE);
                tvTwo.setText("Fixed PF");

                //输入类型为数字是带符号的，允许在开头带正号或者负号
                tv02.setText(NumberUtils.forMatNumber(bb * 0.01));
                tv02.setFilters(new InputFilter[]{new TwoPointLengthFilter()});
                tv02.setVisibility(View.VISIBLE);
                tv03.setVisibility(View.GONE);
                tvRight.setVisibility(View.GONE);
                isChange = false;
                break;
            case 3:
                tv01.setText("Fixed reactive power response mode");
                llTwo.setVisibility(View.VISIBLE);
                tvTwo.setText("Fixed ReactivePower");
                tv03.setText(bc + "");
                tv02.setVisibility(View.GONE);
                tv03.setVisibility(View.VISIBLE);
                tvRight.setVisibility(View.VISIBLE);
                isChange = false;
                break;
            case 4:
                tv01.setText("Characteristic power factor mode");
                llTwo.setVisibility(View.GONE);
                tvRight.setVisibility(View.GONE);
                isChange = false;
                break;
        }

    }

    private void initVoltResponseModeSetting(int bc, int bb, int be) {

        isGetData = true;
        Log.e(TAG, "电网电压响应设置: " + bc);
        Log.e(TAG, "电网电压响应设置: " + bb);
        Log.e(TAG, "电网电压响应设置: " + be);
        this.bc = bc;
        this.bb = bb;
        this.be = be;
        intSelectView();


    }

    /**
     * 发送消息
     */
    private void sandMessage() {
        getLoadingDialog().show();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("电网电压响应设置", "发送的16进制指令: " + DataUtils.hexBytesToString(SocketConfig.getVoltResponseModeSetting()));
                        SocketUtils.sendSerialPort(SocketConfig.getVoltResponseModeSetting());
                    }
                }).start();

            }
        }, 10);
    }


    private String tip;

    /**
     * 退出登录对话框
     */
    private void showTipsDialog(String msg) {
        isChange = false;
        Dialog dialog = PinziDialogUtils.getDialogNotTouchOutside(this, R.layout.dialog_confirm);
        TextView tvTitle = (TextView) dialog.findViewById(R.id.tv_title);
        TextView tvContent = (TextView) dialog.findViewById(R.id.tv_content);
        TextView tvNo = (TextView) dialog.findViewById(R.id.tv_no);
        TextView tvOk = (TextView) dialog.findViewById(R.id.tv_ok);
        tvTitle.setText("tips");
        tvContent.setText(msg);
        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();

            }
        });
        tvNo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        dialog.show();

    }

    /**
     * //监听外来是否要去成功的界面
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MessageEvent event) {
        /* Do something */
        if (EmptyUtils.isNotEmpty(event)
                && EmptyUtils.isNotEmpty(event.getSendMessage())

        ) {

            initSenMessage(event.getSendMessage());
        }
    }

    private void initSenMessage(RxBusBean.SendMessage sendMessage) {

        Log.e("电网电压响应设置", "all-我接收到了查询命令的所有数据(已过滤传输规则中其他数据):" + Arrays.toString(sendMessage.info));
        /***车载终端控制**/
        if (sendMessage != null && sendMessage.readContent[2] == SocketConfig.SEARCH) {
            try {
                getLoadingDialog().dismiss();
                Log.e("电网电压响应设置", "我接收到了查询命令的所有数据(已过滤传输规则中其他数据):" + Arrays.toString(sendMessage.info));
                Log.e("电网电压响应设置", "接受到的最原始的数据:" + DataUtils.ByteArrToHex(sendMessage.readContent));
                Log.e("电网电压响应设置", "前六位是年月日时分秒:" + DataUtils.HexToInt(sendMessage.info[0]) + "年" + DataUtils.HexToInt(sendMessage.info[1]) + "月" + DataUtils.HexToInt(sendMessage.info[2]) + "日" + DataUtils.HexToInt(sendMessage.info[3]) + "时" + DataUtils.HexToInt(sendMessage.info[4]) + "分" + DataUtils.HexToInt(sendMessage.info[5]) + "秒");

                List<String> infoList = Arrays.asList(sendMessage.info);

                int BCIndex = infoList.indexOf("BC");
                int BC = DataUtils.HexToInt(sendMessage.info[BCIndex+2] + sendMessage.info[BCIndex+1]);
                // int BC = DataUtils.HexToInt(sendMessage.info[9] + sendMessage.info[8]);
                Log.e("电网电压响应设置", "BC: " + BC);


                int BBIndex = infoList.indexOf("BB");
                int BB = DataUtils.HexToInt(sendMessage.info[BBIndex+2] + sendMessage.info[BBIndex+1]);
                // int BB = DataUtils.HexToInt(sendMessage.info[12] + sendMessage.info[11]);
                Log.e("电网电压响应设置", "BB: " + BB);


                int BEIndex = infoList.indexOf("BE");
                int BE = DataUtils.HexToInt(sendMessage.info[BEIndex+2] + sendMessage.info[BEIndex+1]);
                //int BE = DataUtils.HexToInt(sendMessage.info[15] + sendMessage.info[14]);
                Log.e("电网电压响应设置", "BE: " + BE);

                initVoltResponseModeSetting(BC, BB, BE);
            }
            catch (Exception e){

                ToastUitl.showImageToastSuccess(e.getMessage()+" - ");
            }

        }

        //  设置命令
        else if (sendMessage != null && sendMessage.readContent[2] == SocketConfig.SETTING) {
            isSetting = false;
            getLoadingDialog().dismiss();
            String hexString = DataUtils.ByteArrToHex(sendMessage.readContent);
            Log.e(TAG, "电网电压响应设置总的数据:" + hexString);
            Log.e("电网电压响应设置命令", "我接收到了实时信息的所有数据(已过滤传输规则中其他数据):" + Arrays.toString(sendMessage.info));
            Log.e("电网电压响应设置命令", "前六位是年月日时分秒:" + DataUtils.HexToInt(sendMessage.info[0]) + "年" + DataUtils.HexToInt(sendMessage.info[1]) + "月" + DataUtils.HexToInt(sendMessage.info[2]) + "日" + DataUtils.HexToInt(sendMessage.info[3]) + "时" + DataUtils.HexToInt(sendMessage.info[4]) + "分" + DataUtils.HexToInt(sendMessage.info[5]) + "秒");
            int result = DataUtils.HexToInt(sendMessage.info[6]);
            Log.e(TAG, "电网电压响应设置命令accept: " + result);

            if (result == 0 || result == 1 || result == 2 || result == 3 || result == 4 || result == 6) {
                tip = errors[result];
                showTipsDialog(tip);
            } else {
                if (result == 5) {

                    int id = DataUtils.HexToInt(sendMessage.info[7]);
                    double min;
                    double max;
                    //16进制ID
                    String idStr = DataUtils.toHexString(id);
                    if (
                            "bb".equals(idStr)) {
                        min = DataUtils.HexToInt(sendMessage.info[9] + sendMessage.info[8]) * 0.01;
                        max = DataUtils.HexToInt(sendMessage.info[11] + sendMessage.info[10]) * 0.01;

                    } else {
                        min = DataUtils.HexToInt(sendMessage.info[9] + sendMessage.info[8]);
                        max = DataUtils.HexToInt(sendMessage.info[11] + sendMessage.info[10]);
                    }

                    if("bb".equals(idStr)){
                        tip = "Fixed PF is between ±" + NumberUtils.forNormalMatNumber(min) + " and " +  NumberUtils.forNormalMatNumber(max);
                    }
                    if("bc".equals(idStr)){
                        tip = "Fixed ReactivePower between " + NumberUtils.forNormalMatNumber(min) + " and " +  NumberUtils.forNormalMatNumber(max);
                    }

                    showTipsDialog(tip);


                } else {
                    tip = "System abnormal, error code is" + sendMessage.info[6];
                    showTipsDialog(tip);
                }
            }

        }
    }
}
